var request=require("request");
var Msdb=require("./db/Msdb.js");
var cookieParser=require("cookie-parser");
var moment = require('moment');
const crypto = require('crypto');
var urlencode = require('urlencode');
var Redisdb=require("./db/Redisdb.js");
var Mysqldb = require('./db/Mysqldb.js');


class Wechat{
  constructor(name,age){
    this.name=name;
    this.age=age;
  }

//静态声明可以直接引入模块后.ttt调用
static ttt(){
  console.log("3333");
};

async ifbd(id){
  var db=new Mssqldb("SS");
  var numresult=await db.query("select * from wx_userinfo where dd_openid='"+id+"' and dd_mobile is not null" );
  return numresult.length;
}


async testaws(){
  var nsrcret="XGvpXL9S0AA27Hvlwliv7KKWLYOZEBkj1g5B2Zjl";
  var ndate="20210221";
var naws="us-east-1";
  var signaturestr = crypto.createHmac('sha256',nsrcret).update(signarr).update(signarr).update(signarr).digest("base64");
 

}




async getjsapiticket(qdurl){

  //console.log("code=="+req.body.code);
  var appid="wx4dd6932f3c4fa5ac";
  var appsecret="462ae7b22773776bd2af1ea033acb39b";
    var gettokenurl=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=`+appid+`&secret=`+appsecret;

  var accessTokenall=null;
    var raccesstoken=await new Promise((resolve) => {
   Redisdb.get('raccesstoken', function(err,result){
    if (err) {
      console.log(err);
      resolve(null)
      return;
    }
    console.log("****"+result);
    resolve(result)
  })

 });

  if(raccesstoken==null){
  accessTokenall = await new Promise((resolve) => {
  request(gettokenurl, async function (error, response, body) {
    console.log('request1')
    if (!error && response.statusCode == 200) {
      console.log(body)
      var access_token_obj=JSON.parse(body);
      console.log("body-----%%%%%"+body)
    Redisdb.set('raccesstoken', JSON.parse(body).access_token, '7000', function(err,result){
            if (err) {
              console.log(err);
              return;
            }
            console.log('插入数据结果:'+result);
          })

resolve(access_token_obj.access_token);

}else ;

})
});
}
else {
  accessTokenall=raccesstoken
}

  console.log("accessTokenall----"+accessTokenall);

  //到这一步获取了token并用redis缓存


var getticketurl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessTokenall+"&type=jsapi"
var jsticket=null;
    var r_jsticket=await new Promise((resolve) => {
   Redisdb.get('r_jsticket', function(err,result){
    if (err) {
      console.log(err);
      resolve(null)
      return;
    }
    console.log("**r_jsticket**"+result);
    resolve(result)
  })

 });


    if(r_jsticket==null)
{
    jsticket = await new Promise((resolve) => {
  request(getticketurl, async function (error, response, body) {

    if (!error && response.statusCode == 200) {
      console.log(body)
      var jsticket_obj=JSON.parse(body);

    Redisdb.set('r_jsticket', JSON.parse(body).ticket, '7000', function(err,result){
            if (err) {
              console.log(err);
              return;
            }
            console.log('插入数据结果:'+result);
          })

resolve(jsticket_obj.ticket);

}else ;

})
  })
}
else
{
jsticket=r_jsticket;
}



console.log("拿到的jstickeet门票--"+jsticket)

 var timestamp=new Date().getTime();
 var url=qdurl;

 var noncestr = new Date().getTime() + "1234";

 var mingwen="jsapi_ticket="+jsticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
console.log("mingwen--"+mingwen);
  var signature =  crypto.createHash('sha1').update(mingwen).digest('hex').toLowerCase();
console.log("signaturestr--"+signature);

var rtjo={
timestamp:timestamp,
url:url,
noncestr:noncestr,
signature:signature,
jsapi_ticket:jsticket
}

return rtjo;



}


//微信静态声明引入模块后，需要new再.ttt调用，
async auth(req, res){
  console.log("code=="+req.query.code);
  var code=req.query.code;
  var appid="wx4dd6932f3c4fa5ac";
  var appsecert="462ae7b22773776bd2af1ea033acb39b";
var gettokenurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecert+"&code="+code+"&grant_type=authorization_code";//根据前端code获得accesstoken。
var access_token_obj="";
var openid="";
var headimgurl="";
var province="";
var city="";
var country="";
var nickname="";
var sex="";
    var id="";
    var autharea="";

for(var i=0;i<6;i++) //6位随机数，用以加在时间戳后面。
{
  id += Math.floor(Math.random()*10);
}
id = new Date().getTime() + id;
console.log('request0')
const gg = await new Promise((resolve) => {
  request(gettokenurl, async function (error, response, body) {
    console.log('request1')
    if (!error && response.statusCode == 200) {
      //  console.log(body) // Show the HTML for the baidu homepage.
      var access_token_obj=JSON.parse(body);
    // console.log("ACCESS_TOKEN-----"+access_token_obj.access_token);
    // console.log("OPEN_ID-----"+access_token_obj.openid);
    var getuerinfourl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token_obj.access_token+"&openid="+access_token_obj.openid+"&lang=zh_CN";
// 拉取用户信息




var cc= await new Promise((resolve) => {
  request(getuerinfourl,async function (error, response, body) {
    console.log('request2')
    if (!error && response.statusCode == 200) {
        console.log("最后获取到的信息----"+body) // Show the HTML for the baidu homepage.
        access_token_obj=JSON.parse(body);
        openid=access_token_obj.openid;
        headimgurl=access_token_obj.headimgurl;
        headimgurl.replace(/\\/, "");
      console.log("headimgurl----"+headimgurl);
      province=access_token_obj.province;
      city=access_token_obj.city;
      country=access_token_obj.country;
      nickname=access_token_obj.nickname;
      sex=access_token_obj.sex;
    // console.log("openid"+openid);

    var db=new Mysqldb("fsdfsdfsdf");
    var recoedsetsnum=await db.query("select * from wx_userinfo where openid='"+openid+"'");
    if(recoedsetsnum.length=='0'){
      console.log("不存在");     

db.update("insert into wx_userinfo (id,openid,nickname,sex,headimgurl) values "
  +"('"+id+"','"+openid+"','"+nickname+"','"+sex+"','"+headimgurl+"')");

}
else {console.log("该用户已经存在");

db.update("update wx_userinfo set headimgurl='"+headimgurl+"' where openid='"+openid+"'");


 }

}
else;
resolve(3);
})
})


}

resolve(3);
});
})


return {openid:openid,headimgurl:headimgurl,nickname:nickname};
};








}

module.exports = Wechat;

